#!/bin/bash

# glabal_github_proxy="https://gh.api.99988866.xyz/"
glabal_github_proxy=""
#    / **  
#    * 文件名：zsh.sh 安装与配置
#    * 版权： Copyright 谢振斌  All Rights Reserved.  
#    * 描述： Shell模板  
#    * 修改内容：新增  
#    * 修改人： 谢振斌  
#    * 修改时间：2021-3-23  
#    */  

#    / **  
#    *〈一句话功能简述〉  
#    *〈功能详细描述〉  
#    * @param [参数1] [参数1说明]  
#    * @param [参数2] [参数2说明]  
#    * @return [返回类型说明]  
#    * @exception/throws [违例类型] [违例说明]  
#    * @see [类、类#方法、类#成员]  
#    * @deprecated  
#    */  
function fun1()  
{  
	echo "helld world !"

	# 在shell中：
	# $0: 获取当前脚本的名称
	# $#: 传递给脚本的参数个数
	# $$: shell脚本的进程号
	# $1, $2, $3...：脚本程序的参数
}

#    / **  
#    *〈 判断shell系统类型 〉  
#    *〈功能详细描述〉  
#    * @param [参数1] [参数1说明]  
#    * @param [参数2] [参数2说明]  
#    * @return [返回类型说明]  String [linux、osx、bsd] 
#    * @exception/throws [违例类型] [违例说明]  
#    * @see [类、类#方法、类#成员]  
#    * @deprecated  
#    */  
function getShellOStype()
{
    SHELL_PLATFORM='unknown';
    ## echo "[Debug] SHELL_PLATFORM=${SHELL_PLATFORM}"

    ## echo $OSTYPE | tr '[A-Z]' '[a-z]'"
    shellostypestring=`echo $OSTYPE`;
    ## echo "[Debug] shellostypestring=${shellostypestring}"

    ## 从字符串中识别shell系统类型
    case "${shellostypestring}" in
        *'linux'*   ) SHELL_PLATFORM='linux'    ;;
        *'darwin'*  ) SHELL_PLATFORM='osx'      ;;
        *'bsd'*     ) SHELL_PLATFORM='bsd'      ;;
    esac

    # if [[ $SHELL_PLATFORM == 'linux' || $SHELL_PLATFORM == 'bsd' ]]; then
    #    echo "[Debug] linux"
    # elif [[ $SHELL_PLATFORM == 'osx' ]]; then
    #    # $SHELL_PLATFORM == 'bsd'
    #    echo "[Debug] osx Shell"
    # elif [[ $SHELL_PLATFORM == 'bsd' || $SHELL_PLATFORM == 'osx'  ]]; then
    #    echo "[Debug] bad shell"
    # else
    #    echo "[Debug] unknown"
    # fi

    # 返回值
    echo $SHELL_PLATFORM;
}



#    / **  
#    *〈获得发行版本名称〉  
#    *〈功能详细描述〉  
#    * @param [参数1] [参数1说明]  
#    * @param [参数2] [参数2说明]  
#    * @return [返回类型说明]  
#    * @exception/throws [违例类型] [违例说明]  
#    * @see [类、类#方法、类#成员]  
#    * @deprecated  
#    */  
function getDistName()
{
    if grep -Eqii "Arch Linux" /etc/issue || grep -Eq "Arch Linux" /etc/*-release; then
        DISTRO='Arch Linux'
        PM='pacman'
    elif grep -Eqii "CentOS" /etc/issue || grep -Eq "CentOS" /etc/*-release; then
        DISTRO='CentOS'
        PM='yum'
    elif grep -Eqi "Red Hat Enterprise Linux Server" /etc/issue || grep -Eq "Red Hat Enterprise Linux Server" /etc/*-release; then
        DISTRO='RHEL'
        PM='yum'
    elif grep -Eqi "Aliyun" /etc/issue || grep -Eq "Aliyun" /etc/*-release; then
        DISTRO='Aliyun'
        PM='yum'
    elif grep -Eqi "Fedora" /etc/issue || grep -Eq "Fedora" /etc/*-release; then
        DISTRO='Fedora'
        PM='yum'
    elif grep -Eqi "Debian" /etc/issue || grep -Eq "Debian" /etc/*-release; then
        DISTRO='Debian'
        PM='apt'
    elif grep -Eqi "Ubuntu" /etc/issue || grep -Eq "Ubuntu" /etc/*-release; then
        DISTRO='Ubuntu'
        PM='apt'
    elif grep -Eqi "Raspbian" /etc/issue || grep -Eq "Raspbian" /etc/*-release; then
        DISTRO='Raspbian'
        PM='apt'
    else
        DISTRO='unknow'
    fi

    # 返回值
    echo $DISTRO;
}

#    / **  
#    *〈 fzf cd 自定义扩展命令 〉  
#    *〈 该脚本的主函数 〉  
#    * @param [无]  
#    * @return [无]  
#    * @exception/throws [无]  
#    * @deprecated  
#    */  
function fzfCustomCommand()  
{
    # 配置文件位置
    # configFilePath = "~/.zshrc"
    configFilePath=$1;
    # 添加的配置内容
    configScriptString="
    vimf(){
        vim $(fzf --preview 'cat {}')
    }
    nvimf(){
        nvim $(fzf --preview 'cat {}')
    }

    # 使用cd fd fzf 查找与切换目录
    cdf(){
       # cd $(fd -p '/' -t d | fzf )
       # cd $(fd -p ’/‘ -t d | fzf --preview 'ls -alh {}')
       cd $(fd  -t  d | fzf --preview 'ls -ahl {}' )
    }
    ";

    # 在配置文件末尾添加
    #echo "$configScriptString" >> ${configFilePath};
    echo "${configScriptString}" >> ${configFilePath};
}

#    / **  
#    *〈 zsh 下 autojump 自定义扩展命令 〉  
#    *〈 该脚本的主函数 〉  
#    * @param [无]  
#    * @return [无]  
#    * @exception/throws [无]  
#    * @deprecated  
#    */  
function autojumpCustomCommand()  
{
    # 配置文件位置
    # configFilePath = "~/.zshrc"
    configFilePath=$1;
    # 添加的配置内容
    configScriptString="
    # autojump 配置
    source /usr/share/autojump/autojump.bash

    # 命令缩写、别名
    alias j=autojump

    ";

    # 在配置文件末尾添加
    echo "${configScriptString}" >> ${configFilePath};
}

#    / **  
#    *〈 安装软件 从git仓库〉  
#    *〈功能详细描述〉  
#    * @param [参数1] [git仓库地址]  
#    * @param [参数2] [本地存放地址]  
#    * @param [参数3] [克隆后执行的安装命令] 
#    * @return [返回类型说明]  
#    * @exception/throws [违例类型] [违例说明]  
#    * @see [类、类#方法、类#成员]  
#    * @deprecated  
#    */  
function installSoftwareFormGit()
{

    echo "[INFO] 开始 从git仓库安装软件 "
    pluginsName=$1
    echo "[Debug] pluginsName="${pluginsName}
    pluginsPath=$2
    echo "[Debug] pluginsPath="${pluginsPath}
    echo "[INFO] 安装插件："${pluginsName}
    executableInstallCmdStr=$3
    echo "[Debug] executableInstallCmdStr="${executableInstallCmdStr}

    # 判断是否路径是否已经存在
    if [ ! -d "$pluginsPath" ]; then
      echo "Installing "${pluginsName}
      #URL="https://github.com/"
      #URL="https://hub.fastgit.org/"
      # URL="https://hub.fastgit.xyz/"
    #   URL="https://ghproxy.com/https://github.com/"
      URL="${glabal_github_proxy}https://github.com/"
      # URL="http://github.com/"
      if [ -x "$(which git)" ]; then
        # 命令拼接
        #cmdStr="ln -s  "${dir}"/zshrc-oh-my-sh  "${HOME}"/.zshrc"
        cmdStr="git clone "${URL}${pluginsName}" "${pluginsPath}
        echo "执行命令: ${cmdStr}"
        ${cmdStr}
        echo "[INFO] 安装插件"${pluginsName}"安装完成！"
        # 
        if [ ! -d "$pluginsPath" ]; then

            # git克隆完成，执行相关安装命令
            echo "git克隆完成，执行命令: ${executableInstallCmdStr}"
            ${executableInstallCmdStr}
        fi
      else
        echo "[ERROR]: 请先安装 git !!"
        exit
      fi
      if [ ! $? -eq 0 ]; then
            echo ""
            echo "[ERROR]: 克隆${pluginsName}仓库中出错!!"
            exit
      else
            # 进入克隆目录
            cmdStr="cd "${pluginsPath}
            echo "执行命令: ${cmdStr}"
            ${cmdStr}
            # 查看目录
            cmdStr="pwd"
            echo "执行命令: ${cmdStr}"
            ${cmdStr}

            # 退回原来目录
            cmdStr="cd -"
            echo "执行命令: ${cmdStr}"
            ${cmdStr}
      fi
    else
        echo "[INFO] ${pluginsName}已经存在！"
        # 进入目录执行 更新
        cmdStr="cd "${pluginsPath}
        echo "执行命令: ${cmdStr}"
        ${cmdStr}
        
        cmdStr="git pull"
        # git克隆完成，执行相关安装命令
        echo "执行命令: ${cmdStr}"
        ${cmdStr}

        # 退回原来目录
        cmdStr="cd -"
        echo "执行命令: ${cmdStr}"
        ${cmdStr}
    fi
}


#    / **  
#    *〈 安装软件 〉  
#    *〈功能详细描述〉  
#    * @param [参数1] [软件名称]  
#    * @param [参数2] [用来判断是否已经安装的软件名称，可为空，为空则，与参数1来判断是否存在]  
#    * @return [返回类型说明]  
#    * @exception/throws [违例类型] [违例说明]  
#    * @see [类、类#方法、类#成员]  
#    * @deprecated  
#    */  
function installSoftware()
{
    echo "[INFO] 安装软件";
    softwareName=$1;
    echo "[Debug] softwareName="${softwareName};
    # 判断是否已经安装
    #cmdStr="which ${softwareName}"
    #echo "[Debug] cmdStr="${cmdStr}
    #if [ ! -x "$( which ${softwareName} )" ]; then
    #    echo "[Debug] 未安装软="${softwareName}
    #else
    #    echo "[Debug] 已经安装软="${softwareName}
    #fi
    #exit
    softwareName2=$2;
    if [  ! $softwareName2 ];then
        echo "[INFO] 软件安装与用来判断是否安装的名称相同"
        softwareName2=${softwareName};
        echo "[Debug] softwareName2="${softwareName2};
    else
        echo "[INFO] 软件安装名称与用来判断是否安装的名称不同！";
        #softwareName2=$2;
        echo "[Debug] softwareName2="${softwareName2};
    fi
    echo "[INFO] 判断系统中是否已经存在"${softwareName2};
    if [ ! -x "$( which ${softwareName2} )" ]; then
        echo "[INFO] 软件${softwareName}未安装！"
        # 获取当前shell系统（判断是mac、还是linux）
        shellSystemType=$(getShellOStype)
        echo "[Debug] shellSystemType="${shellSystemType}
        if [ "$shellSystemType" == "linux" ]; then
            # 获取当前系统发行版本
            linuxSystemDistType=$(getDistName)
            echo "[Debug] linuxSystemDistType="${linuxSystemDistType}
            # 命令拼接
            #cmdStr="ln -s  "${dir}"/zshrc-oh-my-sh  "${HOME}"/.zshrc"
            #cmdStr="git clone "${URL}${pluginsName}" "${pluginsPath}
            #echo "执行命令: ${cmdStr}"
            #${cmdStr}
            if [ "$linuxSystemDistType" == "CentOS" ]; then
                echo "[Debug] ======= CentOS"
                # 执行另一个脚本
                # /bin/bash ./zsh1.sh  
                #cmdStr="ln -s  "${dir}"/zshrc-oh-my-sh  "${HOME}"/.zshrc"
                cmdStr="yum install "${softwareName}
                echo "执行命令: ${cmdStr}"
                ${cmdStr}
            elif [ "$linuxSystemDistType" == "Arch Linux" ] ; then
                echo "[Debug] ======= Arch Linux"
                cmdStr="yay -S "${softwareName}
                echo "执行命令: ${cmdStr}"
                ${cmdStr}
            else
                echo "[Debug] ======= unknow linux dist"
                echo "[INFO] 不知道当前linux系统是什么发行版本，不知到该用什么包管理软件进行安装！软件${systemType}！"
            fi
      elif [ "$shellSystemType" == "osx" ]; then
           echo "[Debug] ======= shellSystemType是darwin，所以是 osx（macOS）"
           # 权限设置，解决部分软件无法安装问题：如 lua
           cmdStr="sudo chown -R $(whoami) /usr/local/include /usr/local/lib /usr/local/lib/pkgconfig"
           echo "执行命令: ${cmdStr}"
           ${cmdStr}
           cmdStr="chmod u+w /usr/local/include /usr/local/lib /usr/local/lib/pkgconfig"
           echo "执行命令: ${cmdStr}"
           ${cmdStr}
           # 使用软件包管理器安装软件
           cmdStr="brew install "${softwareName}
           echo "执行命令: ${cmdStr}"
           ${cmdStr}
      else
        echo "[Debug] ======= unknow shell system type"
        echo "[INFO] 不知道当前系统是 linux bsd osx（macOS）！不知道该用什么包管理器安装软件${systemType}！"
      fi 
      if [ ! $? -eq 0 ]; then
        echo ""
        echo "[ERROR]: 安装软件${softwareName}  失败 !!！ 退出"
        exit
      fi
    else
        echo "[INFO] 软件${softwareName}已经存在！"
    fi
}

# 安装oh-my-zsh插件（git clone 模式）
function installohmyzshPlugins()
{
    pluginsName=$1
    echo "[Debug] pluginsName="${pluginsName}

    # 拆分字符串 
    # 原理：
    # ${parameter//pattern/string} 
    # 用string来替换parameter变量中所有匹配的pattern
    # 例子：以 , 拆分字符串
    #  string="hello,shell,split,test" 
    #  array=(${string//,/ }) 
    #  echo "[Debug] 循环输出 array[]所有值="${array[1]}
    # for var in ${array[@]}
    # do
    #    echo $var
    # done
    #  参考 [Shell_Linux Shell 中实现字符串切割的几种方法](https://blog.csdn.net/u010003835/article/details/80750003)

    # 以/ 拆分字符串
    array=(${pluginsName//\// })
    # echo "[Debug] 循环输出 array[]所有值="${array[1]}
    # for var in ${array[@]}
    # do
    #   echo $var
    # done
    # echo "[Debug] array[1]="${array[1]}
    pluginsPath=${HOME}"/.oh-my-zsh/custom/plugins/"${array[1]}
    #pluginsPath=${ZSH_CUSTOM}"/plugins/"${pluginsName}
    echo "[Debug] pluginsPath="${pluginsPath}

    echo "[INFO] 安装插件："${pluginsName}
    # 判断是否已经存在
    if [ ! -d "$pluginsPath" ]; then
      echo "Installing "${pluginsName}
      #URL="https://github.com/"
      #URL="https://hub.fastgit.org/"
    #   URL="https://ghproxy.com/https://github.com/"
      URL="${glabal_github_proxy}https://github.com/"
      # URL="http://github.com/"
      # URL="https://hub.fastgit.xyz/"
      # URL="https://ghproxy.com/https://github.com/"
      if [ -x "$(which git)" ]; then
        # 命令拼接
        #cmdStr="ln -s  "${dir}"/zshrc-oh-my-sh  "${HOME}"/.zshrc"
        cmdStr="git clone "${URL}${pluginsName}" "${pluginsPath}
        echo "执行命令: ${cmdStr}"
        ${cmdStr}

        echo "[INFO] 安装插件"${pluginsName}"安装完成！"
        # 重载配置
        #source ${HOME}"/.zshrc"
      else
        echo "[ERROR]: please install git  before installation !!"
        exit
      fi
      if [ ! $? -eq 0 ]; then
        echo ""
        echo "ERROR: downloading ${pluginsName}  failed !!"
        exit
      fi
    else
        echo "[INFO] 插件${pluginsName}已经存在！"
    fi
}

#    / **  
#    *〈 macOS 下安装 lua 〉  
#    *〈该脚本的主函数〉  
#    * @param [无]  
#    * @return [无]  
#    * @exception/throws [无]  
#    * @deprecated  
#    */  
function macosInstallzlua(){
    # zsh git:(master) ✗ brew install lua
    # Updating Homebrew...
    # ==> Auto-updated Homebrew!
    # Updated 1 tap (homebrew/services).
    # No changes to formulae.

    # Error: The following directories are not writable by your user:
    # /usr/local/include
    # /usr/local/lib
    # /usr/local/lib/pkgconfig

    # You should change the ownership of these directories to your user.
    #   sudo chown -R $(whoami) /usr/local/include /usr/local/lib /usr/local/lib/pkgconfig

    # And make sure that your user has write permission.
    #  chmod u+w /usr/local/include /usr/local/lib /usr/local/lib/pkgconfig
    sudo chown -R $(whoami) /usr/local/include /usr/local/lib /usr/local/lib/pkgconfig
    chmod u+w /usr/local/include /usr/local/lib /usr/local/lib/pkgconfig

    brew install lua

}

#    / **  
#    *〈流程控制〉  
#    *〈该脚本的主函数〉  
#    * @param [无]  
#    * @return [无]  
#    * @exception/throws [无]  
#    * @deprecated  
#    */  
function processControlMain()  
{  
    # 打印当前系统时间  
    echo "Start..."  
    date  

    # 此处是你的代码  
    # ...  
    # fun1

    # 检查与安装 oh-my-zsh   Install oh-my-zsh if not exist
    OHMYZSH="$HOME/.oh-my-zsh"
    if [ ! -d "$OHMYZSH" ]; then
      echo "Installing oh-my-zsh ..."
      # URL="https://github.com/robbyrussell/oh-my-zsh.git"
      # URL="https://hub.fastgit.xyz/robbyrussell/oh-my-zsh.git"
    #   URL="https://ghproxy.com/https://github.com/robbyrussell/oh-my-zsh.git"
      URL="${glabal_github_proxy}https://github.com/robbyrussell/oh-my-zsh.git"
      if [ -x "$(which git)" ]; then
        echo "git 克隆 oh-my-zsh 到 ~/.oh-my-zsh"
        git clone "$URL" "$OHMYZSH"
        /bin/bash ~/.oh-my-zsh/tools/install.sh
        # 重载配置
        source ${HOME}"/.zshrc"
      else
        echo "ERROR: please install git  before installation !!"
        exit
      fi
      if [ ! $? -eq 0 ]; then
        echo ""
        echo "ERROR: downloading oh-my-zsh ($URL) failed !!"
        exit
      fi;

      echo "move $TMPFILE to $ANTIGEN"
    fi

    # 安装插件 zsh-autosuggestions
    # git clone https://hub.fastgit.org/zsh-users/zsh-autosuggestions $ZSH_CUSTOM/plugins/zsh-autosuggestions
    # 安装插件 zsh-syntax-highlighting 
    # git clone https://hub.fastgit.org/zsh-users/zsh-syntax-highlighting $ZSH_CUSTOM/plugins/zsh-syntax-highlighting
    installohmyzshPlugins "zsh-users/zsh-autosuggestions"

    # 安装命令提示插件 zsh-users/zsh-autosuggestions
    #git clone http://github.com/zsh-users/zsh-autosuggestions $ZSH_CUSTOM/plugins/zsh-autosuggestions
    #git clone http://hub.fastgit.org/zsh-users/zsh-autosuggestions $ZSH_CUSTOM/plugins/zsh-autosuggestions

    # 安装命令提示插件（有颜色） zsh-syntax-highlighting 
    #git clone https://github.com/zsh-users/zsh-syntax-highlighting $ZSH_CUSTOM/plugins/zsh-syntax-highlighting
    #git clone https://hub.fastgit.org/zsh-users/zsh-syntax-highlighting $ZSH_CUSTOM/plugins/zsh-syntax-highlighting
    installohmyzshPlugins "zsh-users/zsh-syntax-highlighting"
    
    # 安装命令提示插件（有颜色）zdharma/fast-syntax-highlighting
    # git clone https://hub.fastgit.org/zdharma/fast-syntax-highlighting ~/.zsh/fast-syntax-highlighting
    #git clone https://github.com/zdharma/fast-syntax-highlighting $ZSH_CUSTOM/plugins/fast-syntax-highlighting
    # installohmyzshPlugins "zdharma/fast-syntax-highlighting"
    
    # 历史命令搜索插件
    # git clone https://github.com/zsh-users/zsh-history-substring-search $ZSH_CUSTOM/plugins/zsh-history-substring-search
    installohmyzshPlugins "zsh-users/zsh-history-substring-search"

    # 补全fzf
    # git clone https://github.com/Aloxaf/fzf-tab $ZSH_CUSTOM/plugins/fzf-tab
    installohmyzshPlugins "Aloxaf/fzf-tab"

    # 一个文件导航器插件 deer
    #git clone https://github.com/Vifon/deer $ZSH_CUSTOM/plugins/deer
    #git clone  https://hub.fastgit.org/Vifon/deer $ZSH_CUSTOM/plugins/deer

    # cdr是一个zsh命令和一些hook脚手架，允许您切换到最近使用的目录。
    #git clone https://github.com/willghatch/zsh-cdr $ZSH_CUSTOM/plugins/zsh-cdr
    #git clone https://hub.fastgit.org/willghatch/zsh-cdr $ZSH_CUSTOM/plugins/zsh-cdr

    # 安装 autojump
    # https://hub.fastgit.org/wting/autojump
    #installSoftware "autojump"

    # 安装 z.lua
    # https://github.com/skywind3000/z.lua
    # https://hub.fastgit.org/skywind3000/z.lua

    # 安装 lua
    installSoftware "lua"
    # 安装 z.lua
    installSoftwareFormGit "skywind3000/z.lua" "${HOME}/.config/z.lua" "ls"

    # 安装 rg（ripgrep）
    installSoftware "ripgrep" "rg"

    # 安装 ack
    installSoftware "ack"

    # 安装 fzf
    installSoftware "fzf"

    # 安装 bat
    installSoftware "bat"

    # 安装 greenclip xclip xdotool dmenu
    #installSoftware "xclip"
    #installSoftware "xdotool"

    
    # 配置
	# 配置文件位置
	#configFilePath=${HOME}"/.zshrc"
    #content="# 添加自定义配置内容 时间：$(date +%Y-%m-%d_%H_%M_%S)"
	#echo ${content} >> ${configFilePath}
	#cat ./zshrc-oh-my-zsh >> ${configFilePath}

	#source ${HOME}"/.zshrc"

	# 添加 autojump 配置
	#autojumpCustomCommand $configFilePath

	# 添加 fzf fd 配置 (执行)
	#fzfCustomCommand $configFilePath

	# 执行另一个脚本
	# /bin/bash ./zsh2.sh
    # 打印当前系统时间  
    date  
    echo "The End."  
}  

# 执行入口 
# 进入脚本目录位置
cd `dirname $0`
# 获取当前脚本目录位置
shellfilepath=`pwd`'/'$0
# 打印脚本目录地址
echo "[INFO]: 脚本地址 "${shellfilepath}

if true  
#if false  
then  
    echo "[Debug] true"
    # 开始执行  从标准输入中读取并同时写入到标准输出和指定的文件上 
    ## 拼接日志文件地址
    #logfilepath=`pwd`'/'$0'.log'
    logfilepath=`pwd`'/'$0'-'$(date +%Y-%m-%d)'.log'
    ## 打印日志文件地址
    echo "[INFO]: 日志地址" ${logfilepath}
    processControlMain  | tee -a ${logfilepath}
else  
    echo "[Debug] false 函数单元测试 "  
    ## 函数单元测试  
    # installohmyzshPlugins "zdharma/fast-syntax-highlighting"
    #installSoftware "git"
    #installSoftware "bat"
    installSoftware "ripgrep" "rg"
    #  
fi  

# 脚本结束  
